﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using OurSite.Business;
using OurSite.Business.Repositories;


namespace OurSite.Web.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {
        #region Protected Properties
        IUserRepository userRepository = new UserRepository();
        #endregion

        public JsonResult Login(string username, string password)
        {
            User user = userRepository.GetByUserName(username, password);
            string message = "The username or password you entered is incorrect.";

            if (user != null)
            {
                string allRoles = string.Empty;
                if (user.Roles != null)
                {
                    foreach (Role role in user.Roles)
                        allRoles += "|" + role.RoleName;
                }
                allRoles = allRoles.EndsWith("|") ? allRoles.Remove(allRoles.Length - 1, 1) : allRoles;

                Session["CurrentUser"] = user;

                FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, allRoles);

                string encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);

                HttpCookie formAuthenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                Response.Cookies.Add(formAuthenticationCookie);
                message = "success";
            }

            return Json(message, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Logoff()
        {
            FormsAuthentication.SignOut();
            return Json("OK", JsonRequestBehavior.AllowGet);
        }
    }
}
